package com.youlai.boot.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.annotation.RepeatSubmit;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.core.security.model.SysUserDetails;
import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.system.model.form.UserForm;
import com.youlai.boot.system.model.form.WorkForm;
import com.youlai.boot.system.model.query.UserPageQuery;
import com.youlai.boot.system.model.query.WorkerQuery;
import com.youlai.boot.system.model.vo.UserPageVO;
import com.youlai.boot.system.model.vo.WorkerPageVO;
import com.youlai.boot.system.service.OrgService;
import com.youlai.boot.system.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

/**
 * @author 张雨润
 * @date 2025/2/22 17:33
 * @Description 工人管理，实际使用user表
 */
@RestController
@RequestMapping("/api/v1/workers")
@RequiredArgsConstructor
public class WorkerController {
    private final UserService userService;
    private final OrgService orgService;

    /**
     * 查询当前隶属登录机构的配送人员
     * @param queryParams
     * @return
     */
    @Operation(summary = "工人分页列表")
    @GetMapping("/page")
    @Log(value = "工人分页列表", module = LogModuleEnum.USER)
    public PageResult<WorkerPageVO> getWorkerPage(@Valid WorkerQuery queryParams) {
        // 获取当前登录对象user的机构id
        Long userId = SecurityUtils.getUserId();
        UserForm user = userService.getUserFormData(userId);
        IPage<WorkerPageVO> result = new Page<>();
        if (user.getOrgId() == null) {
            return PageResult.success(result);
        }

        //查询工人列表
        result = userService.getWorkerPage(queryParams);

        //删选出隶属当前机构工人
        result.getRecords().stream()
                .filter(f -> ObjectUtil.isNotNull(f.getOrgId()))
                .forEach(it -> it.setOrgName(orgService.getOrgFormData(it.getOrgId()).getOrgName()));
        return PageResult.success(result);
    }
    @Operation(summary = "工人表单数据")
    @GetMapping("/{userId}/form")
    @Log(value = "工人表单数据", module = LogModuleEnum.USER)
    public Result<WorkForm> getUserForm(
            @Parameter(description = "用户ID") @PathVariable Long userId
    ) {
        WorkForm formData = userService.getWorkerFormData(userId);
        if(formData.getOrgId()!=null){
            formData.setOrgName(orgService.getOrgFormData(formData.getOrgId()).getOrgName());
        }
        return Result.success(formData);
    }

    @Operation(summary = "新增用户")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:worker:add')")
    @RepeatSubmit
    @Log(value = "新增用户", module = LogModuleEnum.USER)
    public Result<?> saveUser(
            @RequestBody @Valid WorkForm workForm
    ) {
        boolean result = userService.saveWorker(workForm);
        return Result.judge(result);
    }
    @Operation(summary = "修改用户")
    @PutMapping(value = "/{userId}")
    @PreAuthorize("@ss.hasPerm('sys:worker:edit')")
    @Log(value = "修改用户", module = LogModuleEnum.USER)
    public Result<Void> updateUser(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @RequestBody @Valid WorkForm workForm
    ) {
        boolean result = userService.updateWorker(userId, workForm);
        return Result.judge(result);
    }
    @Operation(summary = "删除用户")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:worker:delete')")
    @Log(value = "删除用户", module = LogModuleEnum.USER)
    public Result<Void> deleteUsers(
            @Parameter(description = "用户ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = userService.deleteUsers(ids);
        return Result.judge(result);
    }

}
